Categories
Fastify

Server-Side Development with Fastify — Response Serialization and Request Validation Error Handling

Spread the love

Fastify is a small Node framework for developing back end web apps.

In this article, we’ll look at how to create back end apps with Fastify.

Serialization

We can change the way that responses are serialized.

To do this, we write:

const fastify = require('fastify')({})

const schema = {
  response: {
    '2xx': {
      type: 'object',
      properties: {
        value: { type: 'string' },
        otherValue: { type: 'boolean' }
      }
    },
    201: {
      value: { type: 'string' }
    }
  }
}

fastify.get('/', { schema }, (request, reply) => {
  reply.send({ value: 1, otherValue: 'foo' })
})

const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

We add the response schema with the schema.response property.

We specify the response data type and structure for each status code.

The type specifies the data type of the response.

properties specifies the data type for the properties in the response.

In the GET / request handler, we call reply.send with an object with the properties listed in the schema.

And the properties will automatically be converted to the types specified in the schema.

So we get:

{"value":"1","otherValue":true}

when we make a GET request to / .

We can also specify the response schema in the request.

To do this, we write:

const fastify = require('fastify')({})

fastify.setSerializerCompiler(({ schema, method, url, httpStatus }) => {
  return data => JSON.stringify(data)
})

fastify.get('/', {
  handler (req, reply) {
    reply.send({ id: 1, name: 'Foo', image: 'BIG IMAGE' })
  },
  schema: {
    response: {
      '2xx': {
        id: { type: 'number' },
        name: { type: 'string' }
      }
    }
  }
})

const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

We call fastify.setSerializerCompiler to compile the response.

And we add the schema to the fastify.get method to specify the response schema.

Error Handling

We can change how errors are handled when validation fails.

For example, we can write:

const fastify = require('fastify')({})

const schema = {
  body: {
    type: 'object',
    properties: {
      name: { type: 'string' }
    },
    required: ['name']
  }
}

fastify.post('/', { schema, attachValidation: true }, function (req, reply) {
  if (req.validationError) {
    reply.code(400).send(req.validationError)
  }
  else {
    reply.send('success')
  }
})

const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

We specify the validation schema.

And in the fastify.post method, we pass in an object with the schema and attachValidation set to true .

We check if there are any validation errors with the req.validationError property.

And we get the validation errors with the req.validationError property.

Conclusion

We can change how responses are serialized and how errors are handled with Fastify.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *